const mongoose = require('mongoose')
const utils = require('../utils/index')
// 响应的json数据
const responseData = {}

// 检查文章id
exports.postIdExist = (req, res, next) => {
  const post_id = req.body.post_id || req.params.post_id
  if(!post_id) {
    responseData.code = 500
    responseData.msg = '文章id不能为空'
    responseData.data = {}
    return res.json(responseData)
  }
  if(!mongoose.Types.ObjectId.isValid(post_id)) {
    responseData.code = 500
    responseData.msg = '文章id不是有效的数据类型'
    responseData.data = {}
    return res.json(responseData)
  }
  if(!utils.checkObjecID(post_id)) {
    responseData.code = 500
    responseData.msg = '文章id不合法'
    responseData.data = {}
    return res.json(responseData)
  }
  next()
}

// 检查文章add和edit
exports.postCheck = (req, res, next) => {
  const title = req.body.title
  const content = req.body.content

  if(!title) {
    responseData.code = 500
    responseData.msg = '文章标题不能为空'
    responseData.data = {}
    return res.json(responseData)
  }
  if(!content) {
    responseData.code = 500
    responseData.msg = '文章内容不能为空'
    responseData.data = {}
    return res.json(responseData)
  }
  next()
}
